/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/* 
 * Copyright (c) 2009 City University of Hong Kong
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License m_version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * Author: Wilson Thong (wilsonwk@ee.cityu.edu.hk) 
 */
#include "routing-tools.h"
#include "ns3/log.h"
#include "ns3/ipv4-routing-table-entry.h"
#include "ns3/ipv4-address.h"
#include "ns3/channel.h"

NS_LOG_COMPONENT_DEFINE ("RoutingTools");

namespace ns3 {
namespace eecityu {

Ptr<Ipv4Route>
GetIpv4RouteFrom (const Ipv4RoutingTableEntry& in, Ptr<Ipv4Route> preferredRoute, Ptr<Ipv4> ipv4)
{
  NS_LOG_FUNCTION (in << *preferredRoute << ipv4);

  Ptr<Ipv4Route> out = Create<Ipv4Route> ();

  // set the destination
  out->SetDestination (preferredRoute->GetDestination ());
  // set the gateway
  out->SetGateway (in.GetGateway ());
  // set the source address
  out->SetSource (preferredRoute->GetSource ());
  // set the output net device
  out->SetOutputDevice (ipv4->GetNetDevice (
    in.GetInterface ()
    ));

  return out;
}

Ipv4Address 
GetRemoteAddress (Ptr<PointToPointNetDevice> dev)
{
  NS_LOG_FUNCTION (dev);
  
  // get the net device of at the opposite of the channel
  Ptr<NetDevice> nextDev;
  nextDev = dev->GetChannel ()->GetDevice (0);
  // check which net device on the channel is actually the opposite one
  if (nextDev == dev)
    nextDev = dev->GetChannel ()->GetDevice (1);
  // get the IPv4 address at the opposite side of the cahnnel
  Ptr<Ipv4> nextIpv4 = nextDev->GetNode ()->GetObject<Ipv4> ();
  int32_t nextIfId = nextIpv4->GetInterfaceForDevice (nextDev);
  Ipv4Address remoteAddr = nextIpv4->GetAddress (nextIfId, 0).GetLocal ();

  return remoteAddr;
}

} // namespace eecityu
} // namespace ns3
